import { useQuery } from "@tanstack/react-query";

import { useAuth } from "@/contexts/auth-context";
import { useApiFetch } from "@/lib/api-fetcher";
import type { OutputsPaginated } from "@/lib/types";

const EMPTY_OUTPUTS: OutputsPaginated = {
  items: [],
  meta: {
    total: 0,
    page: 1,
    pageSize: 0,
    pageCount: 0,
  },
};

export interface DailyOutputsQueryOptions {
  initialData?: OutputsPaginated;
  projectId?: string;
  from: string;
  to: string;
  page?: number;
  pageSize?: number;
}

export function useDailyOutputsQuery({
  initialData = EMPTY_OUTPUTS,
  projectId,
  from,
  to,
  page = 1,
  pageSize = 50,
}: DailyOutputsQueryOptions) {
  const fetcher = useApiFetch();
  const { tokens } = useAuth();

  return useQuery<OutputsPaginated, Error>({
    queryKey: [
      "daily-outputs",
      {
        projectId,
        from,
        to,
        page,
        pageSize,
      },
    ],
    queryFn: async () => {
      if (!tokens) {
        return EMPTY_OUTPUTS;
      }

      const params = new URLSearchParams({
        from,
        to,
        page: String(page),
        pageSize: String(pageSize),
      });

      if (projectId) {
        params.set("projectId", projectId);
      }

      return fetcher<OutputsPaginated>({ path: `/outputs?${params.toString()}` });
    },
    initialData,
    enabled: Boolean(tokens && from && to),
    staleTime: 15 * 1000,
  });
}
